﻿using Microsoft.AspNetCore.Hosting;
using System;
using Microsoft.AspNetCore.Builder;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Internal;
using Microsoft.Extensions.Logging;
using XingLucifer.IBase.Enums;
using Kinlo.Entitys;

namespace Kinlo.WebApi
{
    public class Program
    {
        public static async Task StartService(int port, Action<string, MessageLevelType> log)
        {
            try
            {

                var host = Host.CreateDefaultBuilder()
                    .ConfigureServices(service =>
                    {
                        service.AddSingleton(log);
                    })
                    .ConfigureWebHostDefaults(webBuilder =>
                    {
                        webBuilder.ConfigureKestrel(options =>
                        {
                            // 设置最大请求体大小为406000字节（约为396.5KB）
                            options.Limits.MaxRequestBodySize = 406000;
                        })
                        .UseStartup<Startup>()
                        .UseUrls($"http://0.0.0.0:{port}");
                    })
                        .ConfigureLogging(logging =>
                        {
                            logging.ClearProviders();
                            logging.AddDebug();
                        })
                    .Build();

                await host.StartAsync();

                Console.WriteLine($"【WEB服务】启动成功: http://0.0.0.0:{port}");

                log?.Invoke($"【WEB服务】启动成功: http://0.0.0.0:{port}", MessageLevelType.成功);
                // 保持应用程序运行，直到主机关闭
                await host.WaitForShutdownAsync();
            }
            catch (Exception ex)
            {
                log?.Invoke($"【WEB服务】启动失败: {ex}", MessageLevelType.警告);
                Console.WriteLine($"【WEB服务】启动失败: {ex}");
            }
        }

 
    }
}
